package com.woniu.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.woniu.bean.*;
import com.woniu.service.IQQUserService;
import com.woniu.util.HttpResponseResults;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@Log4j2
@RequiredArgsConstructor
@Api(value = "QQ业务模块的API接口" , description = "QQ业务模块的API接口，支持登录和主页API")
public class QQController {

    @ApiModelProperty(value = "操作QQ用户业务层的接口")
    private final IQQUserService qqUserService;

    @ApiOperation(value = "用于用户登录的")
    @PostMapping("/login")
    @ApiImplicitParam(name = "map" , value = "用户名和密码，用户名是qqId，密码是pwd" , required = true , type = "json")
    public HttpResponseResults login(@RequestBody Map<String ,String> map , HttpSession session) {
        HttpResponseResults r = HttpResponseResults.DEFAULT_FAIL;
        try {
            QQUserBean bean = qqUserService.login(map.get("qqid") , map.get("pwd"));
            r = HttpResponseResults.DEFAULT_SUCCESS;
            session.setAttribute("user",bean); // 存到作用域里面了session，30分都有用
        } catch (NullPointerException e) {
            log.error(e.getMessage());
            r.setMsg("用户不存在");
        } catch (Exception e) {
            log.error(e.getMessage());
            r.setMsg(e.getMessage());
        }
        return r;
    }



    // 这种是传统的方式..list.html是再服务器端。
    // 把list.html删除了
    // 前后端分离：list.html放到前端那边的代码库
    //  怎么来获取呢？
    @ApiOperation(value = "登录后进入首页的" )
    @GetMapping("/home")
    public ModelAndView home(ModelAndView mv , HttpSession session) {
        QQUserBean user = (QQUserBean)session.getAttribute("user");
        Long qqid = user.getQqid();
        /*List<QQUserBO> list = qqUserService.findMyQQFriendList(qqid);*/
        IPage<QQUserBO> page = qqUserService.findMyQQFriendListPage(qqid , 1 , 8);
        mv.setViewName("/list.html"); // 视图
        mv.addObject("page",page);
        //  th:each(page.数据列表)
        return mv;
    }

    // 通过js发送异步请求，来获取首页列表的数据.... 已经学会了vue，简单的多

    @GetMapping("/home2")
    public HttpResponseResults home2(@RequestParam(value = "pageIndex" , defaultValue = "1") Integer pageIndex,
                                     HttpSession session) {
        QQUserBean user = (QQUserBean)session.getAttribute("user");
        Long qqid = user.getQqid();
        IPage<QQUserBO> page = qqUserService.findMyQQFriendListPage(qqid , pageIndex , 8);
        HttpResponseResults r = HttpResponseResults.DEFAULT_SUCCESS;
        r.setData(page);
        return r;
    }

}
